/**
 * <b>项目名：</b>hclv-web<br/>
 * <b>包名：</b>com.flea.hclv.controller<br/>
 * <b>文件名：</b>HHotelController.java<br/>
 * <b>版本信息：</b>1.0<br/>
 * <b>日期：</b>2018年9月12日 下午3:29:31<br/>
 * <b>COPYRIGHT 2010-2012 ALL RIGHTS RESERVED 虫子科技</b>-版权所有<br/>
 */
package com.flea.hclv.controller;

import com.alibaba.fastjson.JSONObject;
import com.flea.hclv.constant.HConstant;
import com.flea.hclv.model.entity.HExplain;
import com.flea.hclv.model.entity.HProduct;
import com.flea.hclv.model.entity.HTimeTable;
import com.flea.hclv.model.entity.HTrip;
import com.flea.hclv.model.entity.vo.ProductSearchVo;
import com.flea.hclv.service.HProductService;
import com.flea.hclv.service.HTimeTableService;
import com.flea.hclv.service.HTripService;
import com.flea.hclv.util.Base64;
import com.flea.hclv.util.ServerResponse;
import com.flea.hclv.util.WordUtil;
import com.flea.system.base.util.StringUtil;
import com.flea.system.bean.FleaPage;
import com.flea.system.entity.OrgDept;
import com.flea.system.platform.session.FleaOrgUtils;
import com.flea.system.utils.ControllerResult;
import com.flea.system.utils.FleaStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * @author myflea@163.com
 * @version 1.0
 * @description TODO
 * @createTime 2018年9月12日 下午3:29:31
 * @modifyTime
 */
@Controller

@RequestMapping("/flea/hclv/product/")
public class HProductController {

  Logger logger = LoggerFactory.getLogger(HProductController.class);
  @Autowired
  private HProductService productService;
  @Autowired
  private HTimeTableService hTimeTableService;
  @Autowired
  private HTripService hTripService;

  public static String stripHtml(String content) {
// <p>段落替换为换行
    content = content.replaceAll("<p .*?>", "\r\n");
// <br><br/>替换为换行
    content = content.replaceAll("<br\\s*/?>", "\r\n");
// 去掉其它的<>之间的东西
    content = content.replaceAll("\\<.*?>", "");
// 还原HTML
// content = HTMLDecoder.decode(content);
    return content;
  }

  /**
   * 产品列表，查询自己部门的所有产品，并进行管理
   *
   * @description
   * @methodName queryAll
   * @returnType void
   * @throw
   */
  @RequestMapping("/queryAllForPage")
  public void queryAll(HttpServletRequest request, FleaPage<HProduct> paging,
      HttpServletResponse response, String model) {
    FleaPage<HProduct> pageList = productService.findForGird(paging.getCurPage(), paging.getPageSize(), model, request);
    ControllerResult conresult = new ControllerResult(pageList);
    conresult.set(true, "操作成功");
    conresult.WritePagingDataToPage(response, pageList);
  }

  /**
   * 废弃
   *
   * @description TODO
   * @methodName detail
   * @returnType void
   * @throw
   */
  @RequestMapping("/detail")
  public void detail(HttpServletRequest request, HttpServletResponse response,
      @RequestParam("id") String id) {
    HProduct product = productService.queryById(id);
    ControllerResult conresult = new ControllerResult(true, "操作成功", product);
    conresult.WriteToPage(response);
  }

  /**
   * 产品添加
   *
   * @description TODO
   * @methodName save
   * @returnType void
   * @throw
   */
  @RequestMapping("save")
  public void save(HttpServletRequest request, HttpServletResponse response) {
    String productJSON = request.getParameter("model");
    logger.info("产品添加传入json原始数据:{}", productJSON);
    boolean result = false;
    try {
      result = productService.save(productJSON, FleaOrgUtils.getCurUserUuid(request));
    } catch (Exception e) {
      logger.error("产品添加:", e);
    }
    ControllerResult cResult = new ControllerResult(true, "操作成功", result);
    cResult.WriteToPage(response);
  }

  /**
   * 产品修改：业务描述，1、只有预售状态的产品可以进行修改，对于在售的产品不可就行修改，想修改的话，下架，重新添加新产品 2、修改的内容：产品基本信息；修改形成；修改班期；修改说明描述
   *
   * @description
   * @methodName updateHotel
   * @returnType void
   * @throw
   */
  @ResponseBody
  @RequestMapping("update")
  public ServerResponse<String> update(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    String productJSON = request.getParameter("model");
    /*	boolean result = true;*/

    ServerResponse<String> result = productService
        .update(productJSON, FleaOrgUtils.getCurUserUuid(request));

    return result;
  }
  @ResponseBody
  @RequestMapping("saveTrip")
  public ServerResponse saveTrip(HttpServletRequest request){
    String model = request.getParameter("model");
    try {
      ServerResponse result = hTripService.saveTrip(model,request);
      return result;
    } catch (Exception e) {
    return ServerResponse.createByErrorMessage(e.getMessage());
    }
  }

  @ResponseBody
  @RequestMapping("delete")
  public ServerResponse<Boolean> delete(HttpServletRequest request, HttpServletResponse response,
      @RequestParam("ids") String ids) throws Exception {
    String userId = FleaOrgUtils.getCurUserUuid(request);
    ServerResponse<Boolean> result = productService.delete(ids, userId);
    return result;
  }

  @ResponseBody
  @RequestMapping("updateToOnSale")
  public ServerResponse<Boolean> updateToOnSale(HttpServletRequest request,
      HttpServletResponse response, @RequestParam("ids") String ids) throws Exception {
    String userId = FleaOrgUtils.getCurUserUuid(request);
    ServerResponse<Boolean> result = productService.updateToOnSale(ids, userId);
    return result;
  }

  @ResponseBody
  @RequestMapping("updateToOndown")
  public ServerResponse<Boolean> updateToOndown(HttpServletRequest request,
      HttpServletResponse response, @RequestParam("ids") String ids) throws Exception {
    String userId = FleaOrgUtils.getCurUserUuid(request);
    ServerResponse<Boolean> result = productService.updateToOndown(ids, userId);
    return result;
  }

  @RequestMapping("/queryDetailById")
  public void queryDetailById(HttpServletRequest request, HttpServletResponse response,
      @RequestParam(value = "id", required = false) String id) {
    JSONObject result = productService.queryDetailById(id);

    ControllerResult conresult = new ControllerResult(true, "操作成功", result);
    conresult.WriteToPage(response);
  }

  /**
   * 全局搜索，根据用户的需求，检索出用户需要的产品（线路，出发时间，出发地点，到达地点，人数，旅游方式，酒店，出行方式等）
   *
   * @description TODO
   * @methodName queryDetail
   * @returnType void
   * @throw
   */
  @RequestMapping("/queryDetail")
  public void queryDetail(HttpServletRequest request, HttpServletResponse response,
      @RequestParam(value = "model", required = false) String queryParams,
      FleaPage<HProduct> paging) {

    ProductSearchVo pvo = JSONObject.parseObject(queryParams, ProductSearchVo.class);
    FleaPage<HProduct> result = productService
        .queryDetailForSearch(request, paging.getCurPage(), paging.getPageSize(), pvo);

    ControllerResult conresult = new ControllerResult(true, "操作成功", result);
    conresult.WriteToPage(response);
  }

  /**
   * 只获取自己产品部门，根据用户的需求，检索出用户需要的产品（线路，出发时间，出发地点，到达地点，人数，旅游方式，酒店，出行方式等）
   *
   * @description TODO
   * @methodName queryDetail
   * @returnType void
   * @throw
   */
  @RequestMapping("/queryDetailByOrg")
  public void queryDetailByOrgId(HttpServletRequest request, HttpServletResponse response,
      @RequestParam(value = "model", required = false) String queryParams,
      FleaPage<HProduct> paging) {

    ProductSearchVo pvo = JSONObject.parseObject(queryParams, ProductSearchVo.class);
    if (pvo == null) {
      pvo = new ProductSearchVo();
    }
    FleaPage<HProduct> result = productService
        .queryDetailForSearchByOrgId(request, paging.getCurPage(), paging.getPageSize(), pvo);

    ControllerResult conresult = new ControllerResult(true, "操作成功", result);
    conresult.WriteToPage(response);
  }

  /**
   * 产品检索
   * 检索出用户需要的产品（线路，出发时间，出发地点，到达地点，人数，旅游方式，酒店，出行方式等）
   *
   * @description TODO
   * @methodName queryDetail
   * @returnType void
   * @throw
   */
  @RequestMapping("/queryForSearch")
  public void queryForSearch(HttpServletRequest request, HttpServletResponse response,
      @RequestParam(value = "model", required = false) String queryParams,
      FleaPage<HProduct> paging) {

    ProductSearchVo pvo = JSONObject.parseObject(queryParams, ProductSearchVo.class);
    if (pvo == null) {
      pvo = new ProductSearchVo();
    }
    //只能查看非自营的
    pvo.setProductCategory(HConstant.D_PRODUCR_CATYEGORY_UNSELF);
    FleaPage<HProduct> result = productService
        .queryDetailForSearch(request, paging.getCurPage(), paging.getPageSize(), pvo);

    ControllerResult conresult = new ControllerResult(true, "操作成功", result);
    conresult.WritePagingDataToPage(response, result);
  }

  /**
   * 自家产品搜索
   * 检索出用户需要的产品（线路，出发时间，出发地点，到达地点，人数，旅游方式，酒店，出行方式等）
   *
   * @description TODO
   * @methodName queryDetail
   * @returnType void
   * @throw
   */
  @RequestMapping("/queryCurrOrgForSearch")
  public void queryCurrOrgForSearch(HttpServletRequest request, HttpServletResponse response,
      @RequestParam(value = "model", required = false) String queryParams,
      FleaPage<HProduct> paging) {

    ProductSearchVo pvo = JSONObject.parseObject(queryParams, ProductSearchVo.class);
    if (pvo == null) {
      pvo = new ProductSearchVo();
    }
    String orgId = FleaOrgUtils.getCurrentUserDeptUuid(request);
    pvo.setOrgId(orgId);
    FleaPage<HProduct> result = productService
        .queryDetailForSearch(request, paging.getCurPage(), paging.getPageSize(), pvo);

    ControllerResult conresult = new ControllerResult(true, "操作成功", result);
    conresult.WritePagingDataToPage(response, result);
  }

  @RequestMapping("findByDeptIdForSelect")
  @ResponseBody
  public ServerResponse<List<HProduct>> findByDeptId(HttpServletRequest request) {
    OrgDept orgDept = FleaOrgUtils.getCurrentUserDept(request);
    if (orgDept == null) {
      return ServerResponse.createByErrorMessage("部门信息为空");
    }
    return productService.findByDeptId(orgDept.getDeptUuid());
  }

  /**
   * 添加班期
   */
  @RequestMapping("saveTimeTable")
  @ResponseBody
  public ServerResponse saveTimeTable(HttpServletRequest request) {
    String model = request.getParameter("model");
    try {
      ServerResponse result = hTimeTableService.saveBatch(model, request);
      return result;
    } catch (Exception e) {
      return ServerResponse.createByErrorMessage(e.getMessage());
    }
  }

  /**
   *
   * @return
   */
  @RequestMapping("findTimeTableByProductId")
  @ResponseBody
  public ServerResponse<FleaPage<HTimeTable>> findTimeTableByProductId(HttpServletRequest request, FleaPage<HTimeTable> paging) {
    String productId = request.getParameter("model");

    if (StringUtil.isEmpty(productId)) {
      return ServerResponse.createByErrorMessage("产品Id为空");
    }

    try {
      ServerResponse result =  hTimeTableService.getByProductIdPaging(productId,paging.getCurPage(),paging.getPageSize());
      return result;
    } catch (Exception e) {
      return ServerResponse.createByErrorMessage(e.getMessage());
    }

  }
  /**
   *
   * @return
   */
  @RequestMapping("updateTimeTableByProductId")
  @ResponseBody
  public ServerResponse updateTimeTableByProductId(HttpServletRequest request) {
    String model = request.getParameter("model");
    try {
      ServerResponse result = hTimeTableService.updateTimeTable(model, request);
      return result;
    } catch (Exception e) {
      return ServerResponse.createByErrorMessage(e.getMessage());
    }
}
  /**
   * 根据tableId删除 但table记录
   * @return
   */
  @RequestMapping("deleteTableById")
  @ResponseBody
  public ServerResponse deleteTableById(HttpServletRequest request) {
    String model = request.getParameter("model");
    try {
      ServerResponse result = hTimeTableService.deleteById(model, request);
      return result;
    } catch (Exception e) {
      return ServerResponse.createByErrorMessage(e.getMessage());
    }
}
  /**
   * 根据tableIds删除 但table记录
   * @return
   */
  @RequestMapping("deleteTableByIds")
  @ResponseBody
  public ServerResponse deleteTableByIds(HttpServletRequest request) {
    String model = request.getParameter("model");
    try {
      ServerResponse result = hTimeTableService.deleteByIds(model, request);
      return result;
    } catch (Exception e) {
      return ServerResponse.createByErrorMessage(e.getMessage());
    }
}






  /**
   * 当初产品详情，包括行程,简称导出行程单
   * @param request
   * @param response
   * @return
   */
  @RequestMapping("exportWord")
  @ResponseBody
  public ServerResponse exportWord(HttpServletRequest request, HttpServletResponse response) {
    String productId = request.getParameter("productId");
    if(StringUtil.isEmpty(productId)){
      return ServerResponse.createByErrorMessage("产品ID为空，不合法，请确认后再导出");
    }
    JSONObject json = productService.queryDetailById(productId);
    if(null==json){
      logger.error("根据产品ID:{},获取到的信息产品信息为空",productId);
      return ServerResponse.createByErrorMessage("导出产品信息失败，请联系运维人员");
    }
    logger.debug("根据产品ID:{},获取到的信息产品信息{}",productId,json.toJSONString());
    Map<String, Object> map = (Map<String, Object>) json;
    HProduct product = JSONObject.parseObject(json.get("product").toString(), HProduct.class);
    product.setFeature(transform(product.getFeature()));
    product.setGuarantee(transform(product.getGuarantee()));
    List<HTrip> trips = JSONObject.parseArray(json.get("trip").toString(),HTrip.class);
    List<HExplain> exps =  JSONObject.parseArray(json.get("explains").toString(),HExplain.class);
    for (HExplain exp: exps
    ) {
      if("notes".equals(exp.getUuid())){
        exp.setDescription(transform(exp.getDescription()));
        map.put("notes", exp);
      }
      if(("costs").equals(exp.getUuid())){
        exp.setDescription(transform(exp.getDescription()));
        map.put("costs", exp);
      }
    }
    logger.debug(json.get("explains").toString());

    map.put("product", product);
    map.put("trips",trips);
    try {
      request.setCharacterEncoding("utf-8");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      return ServerResponse.createByErrorMessage(e.getMessage());
    }
    response.setCharacterEncoding("utf-8");

    // 设定输出文件头
    response.setContentType("application/msword");
    logger.debug("exploer   word start-------------------------------");
    // 预定义的模板位置
    String rootPath = this.getClass().getClassLoader().getResource("/") .getPath();
    String templatePath = rootPath + "/template/";
    String tempword = rootPath + "/template/tempword";
    String tmpPath = rootPath + "/template/templogo";


//    Map<String, Object> testMap = new HashMap<>();
//    HProduct entity = new HProduct();
//    entity.setTitle("我就是测试一下子");
//    testMap.put("info", entity);
//    //设置图片显示
//    String attach = tmpPath + "/" + "matiwan-004.jpg";
//    if (!StringUtil.isEmpty(attach)) {
//      String uuidLogoName = FleaStringUtils.getGenerateUUID().toString();
//      String fillLogoName = tmpPath + "/" + uuidLogoName + ".jpg";
//      String logoBase64 = getImageStr(attach, attach);
//      testMap.put("image", logoBase64);
//    } else {
//      testMap.put("image", null);
//    }

//     // 文件名称
    String defaultFileName = "恒昌旅游网产品说明表";
    String fileName = product.getName()==null?defaultFileName:product.getName();
//
    try {
      response.setHeader("Content-disposition", "attachment; filename=" + new String((fileName + ".doc").getBytes("GB2312"),
              "ISO-8859-1"));
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      return ServerResponse.createByErrorMessage(e.getMessage()+"设置文件头信息失败");
    }
//     // 定义输出 流对象
    OutputStream os = null;
//     // 文件输入流对象
    FileInputStream fis = null;

    WordUtil handler = new WordUtil();
    Writer out = null;
    String uuidName = FleaStringUtils.getGenerateUUID();
    String fillWordName = tempword + "/" + uuidName + ".doc";
    File file = null;
    try {

      file = new File(fillWordName);
      FileOutputStream fos = new FileOutputStream(fillWordName);
      out = new OutputStreamWriter(fos, "UTF-8");
      logger.debug(json.get("product").toString());

      handler.write(response, templatePath, "template.xml", map, out);
//      handler.write(response, templatePath, "template.xml", testMap, out);
//
      int b = 1024;
      os = response.getOutputStream();

      fis = new FileInputStream(file);
      byte[] buf = new byte[1024];
      while (-1 != (b = fis.read(buf))) {
        os.write(buf, 0, b);
      }
    } catch (Exception e) {
      e.getStackTrace();
    } finally {
      try {
        os.close();
        fis.close();
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      file.delete();

    }
    logger.debug("exploer   word end-------------------------------");
    return null;
  }

  /**
   * 处理转义字符
   */
  private String transform(String str) {
    if(StringUtil.isEmpty(str)){
      return "";
    }
    str = stripHtml(str);
    if (str.contains("<") || str.contains(">") || str.contains("&")) {
      str = str.replaceAll("&", "&amp;");
      str = str.replaceAll("<", "&lt;");
      str = str.replaceAll(">", "&gt;");
    }

    return str;
  }

  /**
   *
   * @param imgFile
   * @param fillLogoName
   * @return
   */
  public String getImageStr(String imgFile, String fillLogoName) {

    boolean result = true/* FTPClientUtil.downloadFile(imgFile, fillLogoName)*/;
    if (result) {

      File f = new File(fillLogoName);
      InputStream in = null;
      try {
        in = new FileInputStream(f);
      } catch (FileNotFoundException e1) {

        e1.printStackTrace();
      }
      // String imgFile = "d:/0.jpg";

      byte[] data = null;
      try {

        data = new byte[in.available()];
        in.read(data);
        in.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      return Base64.encode(data);
    } else {
      return null;
    }
  }

}
